import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Modal, Typography, Badge, Card, message, Table, Row, Col, Button } from 'antd';
import '@ant-design/compatible/assets/index.css';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import * as G from '../../../utils/common';
import styles from '../../../components/common/PateoTable/TableList.less';

const { Text } = Typography;

const mapStateToProps = (state:any) => ({
  canDataMonitor: state.canDataMonitor,
  loading: state.loading.models["canDataMonitor"],
});

class CanDataMonitor extends PureComponent<any, any> {
  static contextTypes = {};
  
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      brandList: [],
      vehicleSeriesData: [],
      data: [],
      detailModalVisible: false
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      page: 1,
      size: 10
    }
    dispatch({
      type: 'canDataMonitor/postFetchPage',
      payload: { url: '/can/op/network/exceptiondetail/list', ...tempParam },
    });

    this.getBrand()
    // this.initVehicleSeriesData()
  }

  //  获取品牌数据
  getBrand = ()=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'connectQuickConfig/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({ brandList: res.data });
        }
      },
    });
  }

  //  获取品牌下车系数据
  getVehicleSeriesData = () => {
    const brandId = this.searchForm.current && this.searchForm.current.getFieldValue('brandId');
    this.searchForm.current && this.searchForm.current.setFieldsValue({
      seriesId: '',
    })
    brandId && this.props.dispatch({
      type: 'vehicleInfoQuery/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({ vehicleSeriesData: res.data });
        }
      }
    })
  }

  dataFormat = (fields: any) => {
    // console.log(fields)
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      //  YYYY-MM-DD HH:mm:ss
      fields['startTime'] = moment(start).format('YYYY-MM-DD');
      fields['endTime'] = moment(end).format('YYYY-MM-DD');
      delete fields['handleTimeRange'];
      /* if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(1, 'months'))) {
        message.warning('操作时间区间为一个月！');
        return false;
      } else {
        return fields;
      } */
    }
    return fields
  }


  handleFormReset = () => {
    this.setState({
      formValues: {},
      vehicleSeriesData: []
    });
  }

  /* showDetail = (record: any) => {
    setTimeout(() => {
      this.setState({
        detailModalVisible: true,
        data: [
          {
            id: 1,
            name: 'FAPA休眠异常',
            times: 17,
          },
          {
            id: 2,
            name: 'MP5休眠异常',
            times: 50,
          }
        ]
      })
    }, 300)
  } */

  /* handleOk = () => {
    this.setState({
      detailModalVisible: false
    })
  } */

  /* handleCancel = () => {
    this.setState({
      detailModalVisible: false,
      data: []
    })
  } */

  render() {
    const { loading, permissions, canDataMonitor: { pageData: { pagination, rows = []}}, location: { pathname = '/' } } = this.props
    const { formValues, brandList, vehicleSeriesData, data, detailModalVisible } = this.state
    const columns = [
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: '车系',
        dataIndex: 'brandName',
      },
      {
        title: '车型',
        dataIndex: 'styleName',
      },
      {
        title: '整车电源状态',
        dataIndex: 'vehicleBatteryStatus',
      },
      {
        title: '唤醒计数',
        dataIndex: 'config3',
      },
      {
        title: '报警状态',
        dataIndex: 'warningStatus',
        render: (text: any) => text === 2 ? <Text type="danger">报警失败</Text> : text === 1 ? <Text type="danger">报警成功</Text> : '',
      },
      {
        title: '上报时间',
        dataIndex: 'createdDt',
        render: (text: any) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '',
      },
      /* {
        title: '操作',
        dataIndex: 'opt',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看详情',
              key: 'detail',
              auth: 'canData_doDetail',
              onConfirm: () => { this.showDetail(record) },
            },
          ]
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        }
      }, */
    ]
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      rowKey: (record: any) => record.sid,
      dataSource: rows,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    }
    const searchItems = [
      {
        title: 'VIN',
        type: 'input',
        customStyle: 8,
        key: 'vin',
      },
      {
        title: '时间',
        type: 'rangePicker',
        customStyle: 8,
        format: 'YYYY-MM-DD',
        showTime: false,
        style: {with: '100%'},
        key: 'handleTimeRange',
      },
      {
        title: '报警状态',
        type: 'select',
        selectOptions: [{
          label: '未报警',
          value: '0',
        }, {
          label: '已报警',
          value: '1',
        }],
        customStyle: 8,
        key: 'warningStatus',
      },
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        keyValue: ['brandCode', 'brandName'],
        key: 'brandId',
        onChange: (e: any) => {
          this.getVehicleSeriesData()
        }
      },
      {
        title: '车系',
        type: 'select',
        customStyle: 8,
        selectOptions: vehicleSeriesData,
        keyValue: ['code', 'name'],
        key: 'seriesId',
      },
    ]

    /* const lineStyle = {
      fontSize: '14px',
      lineHeight: 2.4,
      textAlign: 'center' as const,
      fontWeight: 'normal',
      color: 'rgba(0, 0, 0, 0.85)',
      border: '1px solid #d9d9d9',
    } */
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => this.searchForm = val}
            searchItems={searchItems}
            fetchParams={{ type: 'canDataMonitor/postFetchPage', url: '/can/op/network/exceptiondetail/list' }}
            extraArgs={{page:1, size:10}}
            saveFormValues={(val:any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'canDataMonitor/postFetchPage', url: '/can/op/network/exceptiondetail/list', extraArgs: {} }}
            formValues={formValues}
            currentName="page"
            pageSizeName="size"
          />
          {/* <Modal
            title="ECU信号详情"
            visible={detailModalVisible}
            footer={null}
            onCancel={() => {
              this.handleCancel()
            }}>
            <table cellPadding="0" cellSpacing="0" style={{width: '100%', borderCollapse: 'collapse', borderSpacing: 0, }}>
              <colgroup>
                <col className="col1" width="100" />
                <col className="col2" width="100" />
              </colgroup>
              <thead>
                <tr>
                  <th style={lineStyle} className="col1">异常名称</th>
                  <th style={lineStyle} className="col2">异常计数</th>
                </tr>
              </thead>
              <tbody>
                {
                  data && data.length > 0 ? (
                    data.map((item: any, index: number) => {
                      return <tr key={item.id}>
                        <td style={lineStyle}>{item?.name}</td>
                        <td style={lineStyle}>{item?.times}</td>
                      </tr>
                    })
                  ) : (
                    <tr>
                      <td style={lineStyle} colSpan={4}>暂无记录</td>
                    </tr>
                  )
                }
              </tbody>
            </table>
          </Modal> */}
        </Card>
      </div>
    )
  }
}
export default connect(mapStateToProps)(CanDataMonitor);
